<template>
  <div>
    <el-upload
      :accept="accept"
      class="avatar-uploader"
      :action="action"
      :show-file-list="false"
      :http-request="uploadFile"
      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <div slot="tip" class="el-upload__tip">只能上传{{accept}}文件，且不超过{{fileSize}}M</div>
    </el-upload>
  </div>
</template>

<script>
  import axios from 'axios'
  import { getUploadToken } from "@/api/system/oss";

  export default {
    name: "AvatarUpload",
    props:{
      accept: {
        type: String,
        default: '.jpg,.png'
      },
      limit: {
        type: Number,
        default: 1
      },
      fileSize: {
        type: Number,
        default: 2
      },
      imageUrl: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        action: 'http://up-z1.qiniup.com/',
        imgUrl: '',
        token: ''
      }
    },
    methods: {
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < this.fileSize;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过' + this.fileSize + 'M!');
        }
        return isLt2M;
      },
      uploadToken() {
        return new Promise(function (resolve,reject) {
          getUploadToken().then(res => {
            if (res.code == 200) {
              resolve(res.data);
            } else {
              this.$message.error('获取凭证出错！');
              reject();
            }
          })
        })
      },
      uploadFile(raw) {
        this.uploadToken().then(token => {
          let formData = new FormData();
          formData.append("file", raw.file);
          formData.append("token", token.token);
          //获取后缀名
          let ext = raw.file.name.substr(raw.file.name.lastIndexOf(".") + 1);
          formData.append("key", token.fileName + "." + ext);
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };
          axios.post(this.action, formData, config).then(res => {
            if (res.status == 200) {
              var dataStr = res.data;
              dataStr = dataStr.substring(0, dataStr.length - 2);
              var dataObj = JSON.parse(dataStr);
              this.imgUrl = dataObj.fileUrl;
              this.$emit("handleAvatarSuccess", this.imgUrl);
            } else {
              this.$message.error('上传出错，请重试！');
            }
          })
        });
      }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
